/***************************************************************************
 *   Copyright (C) 2009 by Zheng Yonglei
 *   zhengyonglei@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "SettingsDialog.h"

SettingsDialog::SettingsDialog(QDialog *parent)
    : QDialog(parent)
{
	ui.setupUi(this);
	mDictModel = new QStandardItemModel(this);
	setDictTable();

	QShortcut* closeShortcut = new QShortcut(QKeySequence(Qt::Key_Escape),  this);
	QObject::connect(closeShortcut,SIGNAL(activated()),this,SLOT(OKButtonClicked()));

	//ui.refreshIntervalEdit->setInputMask("999");
	QObject::connect(ui.forceRefreshCheckbox, SIGNAL(clicked(bool)),this,SLOT(enableForceRefresh(bool)));

	//ui.firstGroupWaitSecMaxEdit->setInputMask("999");
	ui.firstGroupWaitSecMaxEdit->setValue(OPT.firstGroupWaitSecMax);
	//ui.secondGroupWaitSecMinEdit->setInputMask("999");
	ui.secondGroupWaitSecMinEdit->setValue(OPT.secondGroupWaitSecMin);
	ui.autoSpeakCheckBox->setChecked(OPT.autoSpeak);
	connect(ui.settingOKButton, SIGNAL(clicked()), this, SLOT(OKButtonClicked()));
	connect(ui.dictUpButton, SIGNAL(clicked()), this, SLOT(dictsMoveUpButtonClicked()));
	connect(ui.dictDownButton, SIGNAL(clicked()), this, SLOT(dictsMoveDownButtonClicked()));

	ui.yesNoMethodCheckBox->setChecked(OPT.useYesNoTestMethod);
	ui.multiEnglishMethodCheckBox->setChecked(OPT.useMultiEngTestMethod);
	ui.spellMethodCheckBox->setChecked(OPT.useSpellTestMethod);
	ui.multiExpMethodCheckBox->setChecked(OPT.useMultiExpTestMethod);

	ui.mainShadingColor->setPalette(QPalette(OPT.mainShadingColor));
	ui.mainShadingColor->setAutoFillBackground(true);
	mMainShadingColorDialog = new QColorDialog(QColor(OPT.mainShadingColor), this);
	QObject::connect(ui.setMainShadingButton, SIGNAL(clicked()), this, SLOT(showMainShadingColorDialog()));

	ui.selectShadingColor->setPalette(QPalette(OPT.selectShadingColor));
	ui.selectShadingColor->setAutoFillBackground(true);
	mSelectiongShadingColorDialog = new QColorDialog(QColor(OPT.selectShadingColor), this);
	QObject::connect(ui.setSelectShadingButton, SIGNAL(clicked()), this, SLOT(showSelectionShadingColorDialog()));

	mProgramFontDialog = new QFontDialog(OPT.programFont);
	QObject::connect(ui.setProgramFontButton, SIGNAL(clicked()), this, SLOT(showProgramFontDialog()));

	mBrowserFontDialog = new QFontDialog(OPT.wordBrowserFont);
	QObject::connect(ui.setBrowserFontButton, SIGNAL(clicked()), this, SLOT(showBrowserFontDialog()));

	QObject::connect(ui.useQSoundCheckButton, SIGNAL(clicked(bool)), this, SLOT(useQSound(bool)));
	QObject::connect(ui.setSpeakLibButton, SIGNAL(clicked()), this, SLOT(setSoundLibPath()));
}

SettingsDialog::~SettingsDialog()
{

}

void SettingsDialog::showThisDialog()
{
	//cout<<"SettingsDialog::showThisDialog"<<endl;
	ui.languageComboBox->addItem("Chinese");
	ui.languageComboBox->addItem("English");
	for (int i=0; i<ui.languageComboBox->count(); i++)
		if (OPT.language == ui.languageComboBox->itemText(i))
			ui.languageComboBox->setCurrentIndex(i);

	ui.refreshIntervalEdit->setValue(OPT.refreshInterval);
	ui.forceRefreshCheckbox->setChecked(OPT.forceRefresh);
	ui.refreshIntervalEdit->setEnabled(OPT.forceRefresh);

	ui.enableAssociateMapCheckbox->setChecked(OPT.enableAssociateMap);
	ui.yesNoMethodCheckBox->setChecked(OPT.useYesNoTestMethod);
	ui.multiEnglishMethodCheckBox->setChecked(OPT.useMultiEngTestMethod);
	ui.spellMethodCheckBox->setChecked(OPT.useSpellTestMethod);
	ui.multiExpMethodCheckBox->setChecked(OPT.useMultiExpTestMethod);

	ui.firstGroupWaitSecMaxEdit->setValue(OPT.firstGroupWaitSecMax);
	ui.secondGroupWaitSecMinEdit->setValue(OPT.secondGroupWaitSecMin);

	ui.autoSpeakCheckBox->setChecked(OPT.autoSpeak);
	ui.enableSpeakCheckBox->setChecked(OPT.enableSpeak);
	ui.useQSoundCheckButton->setChecked(OPT.useQSound);

	mProgramFontDialog->setCurrentFont(OPT.programFont);
	mBrowserFontDialog->setCurrentFont(OPT.wordBrowserFont);
	QString testString;
	testString = QString("Currently using font: %1").arg(OPT.programFont.family());
	testString.append(QString(" %1.").arg(OPT.programFont.pointSize()));
	ui.programFontTestLabel->setText(testString);
	ui.programFontTestLabel->setFont(OPT.programFont);
	testString = QString("Currently using font: %1").arg(OPT.wordBrowserFont.family());
	testString.append(QString(" %1.").arg(OPT.wordBrowserFont.pointSize()));
	ui.wordBrowserFontTestLabel->setText(testString);
	ui.wordBrowserFontTestLabel->setFont(OPT.wordBrowserFont);

	mMainShadingColorDialog->setCurrentColor(OPT.mainShadingColor);
	mSelectiongShadingColorDialog->setCurrentColor(OPT.selectShadingColor);

	ui.useQSoundCheckButton->setChecked(OPT.useQSound);
	ui.speakCommandEdit->setText(OPT.playSoundCommand);
	ui.speakCommandEdit->setEnabled(!ui.useQSoundCheckButton->isChecked());
	ui.speakLibraryPathEdit->setText(OPT.speakLibPath);

	ui.enableArticleNavCheckBox->setChecked(OPT.enableArticleNav);
	ui.enablePageNavCheckBox->setChecked(OPT.enableHistoryNav);
	ui.enableSearchCheckBox->setChecked(OPT.enableWordBrowserSearch);

	//QWidget::show();
	this->exec();
}

void SettingsDialog::setRefreshInterval()
{
	OPT.forceRefresh = ui.forceRefreshCheckbox->isChecked();
	if (OPT.forceRefresh)
	{
		int rate = ui.refreshIntervalEdit->value();
		OPT.refreshInterval = rate;
		if (OPT.refreshTimer && OPT.refreshInterval > 0)
		{
			OPT.refreshTimer->stop();
			OPT.refreshTimer->start(OPT.refreshInterval);
		}
	}
	else
		OPT.refreshTimer->stop();
}


void SettingsDialog::setDictTable()
{
	cout<<"SettingsDialog::setDictTable"<<endl;
	mDictModel->clear();
	ui.dictTable->setEditTriggers(false);

	QStringList headers;
	headers<<QString(tr("Enabled"));
	headers<<QString(tr("Name"));
	headers<<QString(tr("Mini-display"));
	//headers<<"Spell Hint";

	mDictModel->setHorizontalHeaderLabels(headers);
	ui.dictTable->setModel(mDictModel);
	ui.dictTable->setEditTriggers(false);
	ui.dictTable->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.dictTable->setAlternatingRowColors(true);

	QStringList dictLists = DM.getDictList();
	QStringList queryDictLists = DM.getQueryDictList();
	QStringList ignorePhraseDictLists = DM.getIgnorePhraseDictList();

	mDictModel->setRowCount(0);
	for(int i=0; i<queryDictLists.size(); i++)
	{
		QString dictName = queryDictLists[i];
		QStandardItem *item = new QStandardItem();
		item->setSelectable(true);
		item->setCheckable(true);
		item->setCheckState(Qt::Checked);

		QStandardItem *dict = new QStandardItem(dictName);
		dict->setSelectable(true);

		/*QStandardItem *spellHint = new QStandardItem();
		spellHint->setCheckable(true);
		spellHint->setCheckState(Qt::Unchecked);*/

		QStandardItem *ignorePhrase = new QStandardItem();
		ignorePhrase->setCheckable(true);
		if (ignorePhraseDictLists.contains(dictName))
			ignorePhrase->setCheckState(Qt::Checked);
		else
			ignorePhrase->setCheckState(Qt::Unchecked);

		QList<QStandardItem*> dictRow;
		dictRow.push_back(item);
		dictRow.push_back(dict);
		dictRow.push_back(ignorePhrase);
		mDictModel->insertRow(mDictModel->rowCount(), dictRow);
	}

	for(int i=0; i<dictLists.size(); i++)
	{
		QString dictName = dictLists[i];
		if (queryDictLists.indexOf(dictName) == -1)
		{

			QStandardItem *item = new QStandardItem();
			item->setSelectable(true);
			item->setCheckable(true);
			//item->setSelectable(true);
			item->setCheckState(Qt::Unchecked);
			//mDictModel->setItem(i+queryDictLists.size(), 0, item);

			QStandardItem *dict = new QStandardItem(dictName);
			//dict->setSelectable(true);
			//mDictModel->setItem(i+queryDictLists.size(), 1, dict);

			QStandardItem *ignorePhrase = new QStandardItem();
			ignorePhrase->setCheckState(Qt::Unchecked);
			//mDictModel->setItem(i+queryDictLists.size(), 2, spellHint);

			QList<QStandardItem*> dictRow;
			dictRow.push_back(item);
			dictRow.push_back(dict);
			dictRow.push_back(ignorePhrase);
			mDictModel->insertRow(mDictModel->rowCount(), dictRow);
		}
	}

	ui.dictTable->resizeColumnsToContents();
}

void SettingsDialog::dictsMoveUpButtonClicked()
{
    int currentRow = ui.dictTable->currentIndex().row();
    if (currentRow > 0)
    {
    	mDictModel->insertRow(currentRow - 1, mDictModel->takeRow(currentRow));
    	ui.dictTable->selectRow(currentRow - 1);
    }
}

void SettingsDialog::dictsMoveDownButtonClicked()
{
    int currentRow = ui.dictTable->currentIndex().row();
    if (currentRow < mDictModel->rowCount() - 1)
    {
    	mDictModel->insertRow(currentRow + 1, mDictModel->takeRow(currentRow));
    	ui.dictTable->selectRow(currentRow + 1);
    }
}

void SettingsDialog::updateDictList()
{
	vector<QString> queryDictList;
	for(int i=0; i<mDictModel->rowCount(); i++)
	{
		QStandardItem *item = mDictModel->item(i,0);
		if(item->checkState() == Qt::Checked)
			queryDictList.push_back(mDictModel->item(i,1)->text());
	}
	DM.setQueryDictList(queryDictList);

	vector<QString> ignorePhraseDicts;
	for(int i=0; i<mDictModel->rowCount(); i++)
	{
		QStandardItem *item = mDictModel->item(i,2);
		if(item->checkState() == Qt::Checked)
			ignorePhraseDicts.push_back(mDictModel->item(i,1)->text());
	}
	DM.setIgnorePhraseDictsList(ignorePhraseDicts);

}

void SettingsDialog::setSoundLibPath()
{
	QFileDialog dialog(this, QString(tr("Set sound library path")), OPT.speakLibPath);
	dialog.setFileMode(QFileDialog::Directory);
	dialog.exec();
	if (!dialog.selectedFiles().isEmpty())
	{
		QString dirStr = dialog.selectedFiles().at(0);
		ui.speakLibraryPathEdit->setText(dirStr);
		OPT.speakLibPath = dirStr;
		//cout<<"SettingsDialog::setSoundLibPath-->dirStr="<<dirStr.toUtf8().data()<<endl;
	}
}

void SettingsDialog::OKButtonClicked()
{
	setRefreshInterval();
	updateDictList();

	OPT.language = ui.languageComboBox->currentText();

	OPT.enableAssociateMap = ui.enableAssociateMapCheckbox->isChecked();
	OPT.useYesNoTestMethod = ui.yesNoMethodCheckBox->isChecked();
	OPT.useMultiEngTestMethod = ui.multiEnglishMethodCheckBox->isChecked();
	OPT.useSpellTestMethod = ui.spellMethodCheckBox->isChecked();
	OPT.useMultiExpTestMethod = ui.multiExpMethodCheckBox->isChecked();

	OPT.firstGroupWaitSecMax = ui.firstGroupWaitSecMaxEdit->value();
	OPT.secondGroupWaitSecMin = ui.secondGroupWaitSecMinEdit->value();

	OPT.autoSpeak = ui.autoSpeakCheckBox->isChecked();
	OPT.enableSpeak = ui.enableSpeakCheckBox->isChecked();
	OPT.useQSound = ui.useQSoundCheckButton->isChecked();

	OPT.useQSound = ui.useQSoundCheckButton->isChecked();
	OPT.playSoundCommand = ui.speakCommandEdit->text();
	OPT.speakLibPath = ui.speakLibraryPathEdit->text();

	OPT.enableArticleNav = ui.enableArticleNavCheckBox->isChecked();
	OPT.enableHistoryNav = ui.enablePageNavCheckBox->isChecked();
	OPT.enableWordBrowserSearch = ui.enableSearchCheckBox->isChecked();

	//hide();
	//done(0);
	this->accept();
}

void SettingsDialog::showMainShadingColorDialog()
{
	mMainShadingColorDialog->exec();
	OPT.mainShadingColor = mMainShadingColorDialog->currentColor().name();
	ui.mainShadingColor->setPalette(QPalette(OPT.mainShadingColor));
}

void SettingsDialog::showSelectionShadingColorDialog()
{
	mSelectiongShadingColorDialog->exec();
	OPT.selectShadingColor = mSelectiongShadingColorDialog->currentColor().name();
	ui.selectShadingColor->setPalette(QPalette(OPT.selectShadingColor));
}

void SettingsDialog::showProgramFontDialog()
{
	mProgramFontDialog->exec();
	OPT.programFont = mProgramFontDialog->currentFont();
	this->setFont(OPT.programFont);
	QString testString;
	testString = QString("Currently using font: %1").arg(OPT.programFont.family());
	testString.append(QString(" %1.").arg(OPT.programFont.pointSize()));
	ui.programFontTestLabel->setText(testString);
	ui.programFontTestLabel->setFont(OPT.programFont);
}

void SettingsDialog::showBrowserFontDialog()
{
	mBrowserFontDialog->exec();
	OPT.wordBrowserFont = mBrowserFontDialog->currentFont();
	QString testString;
	testString = QString("Currently using font: %1").arg(OPT.wordBrowserFont.family());
	testString.append(QString(" %1.").arg(OPT.wordBrowserFont.pointSize()));
	ui.wordBrowserFontTestLabel->setText(testString);
	ui.wordBrowserFontTestLabel->setFont(OPT.wordBrowserFont);
}

